package com.hopes.bizz.common.core.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 数字工具类
 *
 * @author: xk
 * @since: 1.0.0
 * @version: [1.0.0, 2020/8/18]
 */
public class NumberUtil {
    public static final Integer INTEGER_TWO = Integer.valueOf(2);

    /**
     *
     * @param b
     * @return
     */
    public static float getFloat(byte[] b) {
        int accum = 0;
        accum = accum | (b[0] & 0xff) << 0;
        accum = accum | (b[1] & 0xff) << 8;
        accum = accum | (b[2] & 0xff) << 16;
        accum = accum | (b[3] & 0xff) << 24;
        System.out.println(accum);
        return Float.intBitsToFloat(accum);
    }


    /**
     * 保留N位小数输出double数字,
     *
     * @param value 数字
     * @return 指定精度的数据
     */
    public static Double toScaledDouble(final Double value, int scale) {
        if (value == null) {
            return null;
        }
        return toScaledDouble(BigDecimal.valueOf(value), scale, RoundingMode.HALF_UP);
    }

    /**
     * 保留2位小数输出double数字
     *
     * @param value 数字
     * @return 指定精度的数据
     */
    public static Double toScaledDouble(final Double value) {
        if (value == null) {
            return null;
        }
        return toScaledDouble(BigDecimal.valueOf(value), INTEGER_TWO, RoundingMode.HALF_UP);
    }

    /**
     * 保留特定位数输出double数字
     *
     * @param value        数字
     * @param scale        精度
     * @param roundingMode 舍入模式
     * @return 指定精度的数据
     */
    public static Double toScaledDouble(final Double value, final int scale, final RoundingMode roundingMode) {
        if (value == null) {
            return null;
        }
        return toScaledDouble(BigDecimal.valueOf(value), scale, roundingMode);
    }

    /**
     * 保留特定位数输出double数字
     *
     * @param value        数字
     * @param scale        精度
     * @param roundingMode 舍入模式
     * @return 指定精度的数据
     */
    public static Double toScaledDouble(final BigDecimal value, final int scale, final RoundingMode roundingMode) {
        if (value == null) {
            return null;
        }
        return value.setScale(scale, (roundingMode == null) ? RoundingMode.HALF_UP : roundingMode).doubleValue();
    }
}
